<?php
require_once('config/config.inc');

	// Provides functions for user account API calls
	class Project{
		function __construct($rwConn,$userObj){
			// Check session for current login
			// If exists validate hash then fill out members
			$this->rwConn = $rwConn;
			$this->userObj = $userObj;
			if($this->rwConn->errno){
				$this->_killMe("Database Error");
			}
		}
		
		function addRelease()
		{
			global $paramArray;
			//verify that both fields are set and not null
       			 if (!isset($paramArray['projectId']) || is_null($paramArray['projectId']) ||
        		 !isset($paramArray['name']) || is_null($paramArray['name']))
        		 {
				$retVal['message'] = "Bad API call";
                	        return $retVal;
			 }

                        $adminCheck = $this->userObj->isAdmin();
                        $isAdmin = $adminCheck['success'];
                        if (!$isAdmin)
                        {
                                $retVal['message'] = "Insufficient privilege";
                                return $retVal;
                        }
			// TODO: Check if projectId is valid
			 // insert query
        		 $sql_query = "insert into `Release` (name, project_id) values ('{$paramArray['name']}', '{$paramArray['projectId']}')";
       			 //echo $sql_query;
			 $sql_result = $this->rwConn->query($sql_query);

			// check for error
			checkDbError();
			if($this->rwConn->affected_rows != 1 )
			{
			    $retVal['message'] = "Insert failed!";
             		    return $retVal;
	      	     	}
			$retVal['releaseId'] = $this->rwConn->insert_id;
			$retVal['success'] = true;
			$retVal['message'] = "Insert was successful";
			return $retVal;
			
	          }
		function delRelease(){
			global $paramArray;
                        $adminCheck = $this->userObj->isAdmin();
                        $isAdmin = $adminCheck['success'];
                        if (!$isAdmin)
                        {
                                $retVal['message'] = "Insufficient privilege";
                                return $retVal;
                        }

			if (!isset($paramArray['release_id']) || is_null($paramArray['release_id'])) {
				$retVal['success'] = false;
				$retVal['message'] = "Bad API call";
				return $retVal;
			}

			$query = "delete from `Release` where release_id={$paramArray['release_id']}";
			$result = $this->rwConn->query($query);
			checkDbError();
			if($this->rwConn->affected_rows != 1 )
                        {
                            $retVal['message'] = "Release doesn't exist";
                            return $retVal;
                        }

			$retVal['success'] = true;
			return $retVal;
		}
		function renameRelease(){
                        global $paramArray;
                        $adminCheck = $this->userObj->isAdmin();
                        $isAdmin = $adminCheck['success'];
                        if (!$isAdmin)
                        {
                                $retVal['message'] = "Insufficient privilege";
                                return $retVal;
                        }

                        if (!isset($paramArray['releaseId']) || is_null($paramArray['releaseId'])) {
                                $retVal['success'] = false;
                                $retVal['message'] = "Bad API call";
                                return $retVal;
                        }
                        if (!isset($paramArray['name']) || is_null($paramArray['name'])) {
                                $retVal['success'] = false;
                                $retVal['message'] = "Bad API call";
                                return $retVal;
                        }

                        $query = "UPDATE `Release` set name = '{$paramArray['name']}'  where release_id={$paramArray['releaseId']} limit 1";
                        $result = $this->rwConn->query($query);
                        checkDbError();
                        if($this->rwConn->affected_rows != 1 )
                        {
                            $retVal['message'] = "Release doesn't exist";
                            return $retVal;
                        }

                        $retVal['success'] = true;
			$retVal['message'] = "Release renamed";
                        return $retVal;
                }
		function listProjects() {
			$userInfo = $this->userObj->getInfo();

			$query = "select proj_id,title from UID_Project_Association JOIN Project ON ";
			$query = $query . "UID_Project_Association.proj_id = Project.project_id where user_id={$userInfo['userId']}";
			$result = $this->rwConn->query($query);
			checkDbError();

			$retVal['success'] = true;
			$retVal['projects'] = array();
			while($row = $result->fetch_row()){
				$retVal['projects'][$row[0]] = $row[1];
			}
			
			return $retVal;
		}
		function renameProject(){
			global $paramArray;
			$adminCheck = $this->userObj->isAdmin();
			$isAdmin = $adminCheck['success'];
			if(!$isAdmin){
				$retVal['message'] = "Insufficient privilege";
			}
			if(!isset($paramArray['projectId'])){
				$retVal['message'] = "projectId missing";
				return $retVal;
			}
			if(!isset($paramArray['projName'])){
				$retVal['message'] = "projName missing";
				return $retVal;
			}
			$sqlQuery = "UPDATE Project SET title='".$paramArray['projName']."'";
			$sqlQuery = $sqlQuery . " WHERE project_id=".$paramArray['projectId'];
			$this->rwConn->query($sqlQuery);
			checkDbError();
			if($this->rwConn->affected_rows != 1){
				$retVal['message'] = "rename failed, projectId may not exist or renaming to same name";
				return $retVal;
			}
			$retVal['success'] = true;
			return $retVal;
		
		}
		function addProject(){
			global $paramArray;
                        $adminCheck = $this->userObj->isAdmin();
                        $isAdmin = $adminCheck['success'];
                        if (!$isAdmin)
                        {
                                $retVal['message'] = "Insufficient privilege";
                                return $retVal;
                        }
                        //verify that both fields are set and not null
                         if (!isset($paramArray['projName']) || is_null($paramArray['projName']))
                         {
                                $retVal['message'] = "Bad API call";
                                return $retVal;
                         }

                         // insert query
                         $sql_query = "insert into Project (title) values ('{$paramArray['projName']}')";
                         $sql_result = $this->rwConn->query($sql_query);

                        // check for error
						checkDbError();
						if($this->rwConn->affected_rows != 1 )
                        {
                            $retVal['message'] = "Insert failed!";
                            return $retVal;
                        }
			$retVal['projectId'] = $this->rwConn->insert_id;
                        $retVal['success'] = true;
                        $retVal['message'] = "Insert was successful";
                        return $retVal;
		}
		function delProject(){
			global $paramArray;
                        $adminCheck = $this->userObj->isAdmin();
                        $isAdmin = $adminCheck['success'];
                        if (!$isAdmin)
                        {
                                $retVal['message'] = "Insufficient privilege";
                                return $retVal;
                        }

			if (!isset($paramArray['projectId']) || is_null($paramArray['projectId'])) {
				$retVal['success'] = false;
				$retVal['message'] = "Bad API call";
				return $retVal;
			}

			$query = "delete from Project where project_id={$paramArray['projectId']}";
			$result = $this->rwConn->query($query);
			checkDbError();
			if($this->rwConn->affected_rows != 1 )
                        {
                            $retVal['message'] = "Project doesn't exist";
                            return $retVal;
                        }

			$retVal['success'] = true;
			return $retVal;
		}
		function listReleases() {
			global $paramArray;

			if (!isset($paramArray['projectId']) || is_null($paramArray['projectId'])) {
				$retVal['success'] = false;
				$retVal['message'] = "Bad API call";
				return $retVal;
			}
			$retVal = $this->memberOfProject($paramArray['projectId']);
			if(!isset($retVal['isMember'])){
				return $retVal;
			}
			$query = "select release_id,name from `Release` where project_id={$paramArray['projectId']}";
			$result = $this->rwConn->query($query);
			checkDbError();

			$retVal['success'] = true;
			$retVal['releases'] = array();
			while($row = $result->fetch_row())
				$retVal['releases'][$row[0]] = $row[1];

			return $retVal;
		}

		function listStickies() {
			global $paramArray;

			if (!isset($paramArray['releaseId']) || is_null($paramArray['releaseId'])) {
				$retVal['success'] = false;
				$retVal['message'] = "Bad API call";
				return $retVal;
			}
			$sql = "SELECT project_id FROM `Release` where release_id = '{$paramArray['releaseId']}'";
			$result = $this->rwConn->query($sql);
			checkDbError();
			$result = $result->fetch_array();
			$result = isset($result[0])?$result[0]:-1;
			$retVal = $this->memberOfProject($result);
			if(!isset($retVal['isMember'])){
				return $retVal;
			} 	
				

			$query = "select * from Sticky where release_id={$paramArray['releaseId']} and is_deleted = 0 order by ordering ASC";
			$result = $this->rwConn->query($query);
			checkDbError();
			$retVal['success'] = true;
			$retVal['stickies'] = array();
			while($row = $result->fetch_assoc()){
				$retVal['stickies'][] = $row;
			}
			return $retVal;
		}


		function assignUser() {
			// NO NEED TODO: proper transaction handling
			global $paramArray;

			if (!isset($paramArray['projectId']) || is_null($paramArray['projectId']) || !is_numeric($paramArray['projectId']) || !is_array($paramArray['users'])) {
				$retVal['success'] = false;
				$retVal['message'] = $paramArray;
				return $retVal;
			}
			// TODO Check if projectId is a valid projectId
			$proj_id = $paramArray['projectId'];
			$tuple = array();
			foreach ($paramArray["users"] as $user_id) {
				$tuple[] = "($user_id,$proj_id)";
			}

			$query = "insert into UID_Project_Association (user_id,proj_id) values ".implode(",",$tuple);
			$this->rwConn->query($query);
			checkDbError();
			$retVal['success'] = true;
			$retVal['message'] = 'Insert Successful';
			return $retVal;
		}
		
		function dissociateUsers(){
			global $paramArray;
                        $adminCheck = $this->userObj->isAdmin();
                        $isAdmin = $adminCheck['success'];
                        if (!$isAdmin)
                        {
                                $retVal['message'] = "Insufficient privilege";
                                return $retVal;
                        }
			if(!$paramArray['projectId']){
				$retVal['success'] = false;
				$retVal['message'] = 'Missing projectId';
				return $retVal;	
			}
			if(!isset($paramArray['users']) || !is_array($paramArray['users'])){
				$retVal['success'] = false;
				$retVal['message'] = "Missing users array";
			}
			$sqlQuery = "DELETE FROM UID_Project_Association WHERE proj_id=";
			$sqlQuery = $sqlQuery . $paramArray['projectId'] . " AND user_id IN ";
			$sqlQuery = $sqlQuery ."(".implode(",",$paramArray['users']) . ")";
			$this->rwConn->query($sqlQuery);
			checkDbError();
			if($this->rwConn->affected_rows == 0 ){
				$retVal['success'] = false;
				$retVal['message'] = "No users were disasociated, bad userIds or projectId";
				return $retVal;
			}
			$retVal['success'] = true;
			return $retVal;
		}	
		function getUsers(){
			global $paramArray;
			if(!isset($paramArray['projectId'])){
				$retVal['success'] = false;
				$retVal['message'] = 'Missing projectId';
				return $retVal;	
			}
			
			$sqlQuery = "SELECT pa.user_id,email,privilege FROM UID_Project_Association AS pa JOIN";
			$sqlQuery = $sqlQuery . " User ON pa.user_id=User.user_id WHERE pa.proj_id =";
			$sqlQuery = $sqlQuery . $paramArray['projectId'];
			$result = $this->rwConn->query($sqlQuery);
			checkDbError();
			$toReturn = array();
			while($row = $result->fetch_assoc()){
                                $toReturn[] = $row;
                        }
			$userInfo = $this->userObj->getInfo();
			$userId = $userInfo['userId'];
			$isMember = false;
			foreach($toReturn as $row){
				if($row['user_id'] == $userId){
					$isMember = true;
					break;
				} 
			}
			if($isMember == false){
				$retVal['success'] = false;
				$retVal['message'] = "You are not associated with this project";
				return $retVal;
			}
			$retVal['success'] = true;
			$retVal['userIds'] = $toReturn;
			return $retVal;
			
		}	
		private function memberOfProject($projectId){
			$myProj = $this->userObj->getMyProject();
			$retVal = array();
			if(!isset($myProj['projectIds'])){
                                $retVal['success'] = false;
                                $retVal['message'] = "User not assigned to a project yet";
                                return $retVal;
                        }
			foreach($myProj['projectIds'] as $projectId2){
                                if($projectId == $projectId2){
                                        $isMember = true;
                                        break;
                                }
                        }
			if($isMember == false){
				$retVal['success'] = false;
				$retVal['message'] = "User not associated with this project";
				return $retVal;
			}
			$retVal['isMember'] = true;
			return $retVal;
		}
		private $rwConn;
		private $projectId;
		private $workingReleaseId;
		private $userObj;
	};

